from pathlib import Path

from pywebio import config, start_server
from pywebio.input import file_upload
from pywebio.output import put_text

SAVE_ROOT = Path("uploads")
SAVE_ROOT.mkdir(exist_ok=True)


def upload_file():
    # Use file_upload to get the uploaded file
    file = file_upload("Select a file to upload", accept="*")

    if file:
        # Get the file name and content
        filename: str = file["filename"]
        content: bytes = file["content"]

        save_path: Path = SAVE_ROOT / filename

        # Save the file to the server
        with open(save_path, "wb") as f:
            f.write(content)

        # Output a success messages
        put_text(f"File {filename} uploaded successfully!")

        print("Uploaded file saved at:", save_path.absolute())


if __name__ == "__main__":
    # Configure the server
    config(title="File Uploader")
    # Start the server
    start_server(upload_file, port=8080, cdn=False)
